package cn.edu.swu.bc.servlet;

import cn.edu.swu.bc.filter.AuthFilter;
import cn.edu.swu.bc.utils.JsonUtils;
import cn.edu.swu.bc.utils.DBUtils;
import cn.edu.swu.bc.entity.Blog;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

public class GetFriendsBlogsServlet extends HttpServlet {

    private static final long serialVersionUID = 119812548834340L;


    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        int page = Integer.parseInt(request.getParameter("page"));
        int id = (Integer) request.getSession().getAttribute(AuthFilter.USER_ID);
        try {
            List<Blog> blogs;
            blogs = DBUtils.getFriendsBlogs(id,page);
            int blogsNum=DBUtils.getBlogsNumber(DBUtils.GetFriendsID(id));
            int pageNum;
            if(blogsNum%5==0)
                pageNum=blogsNum/5;
            else
                pageNum=blogsNum/5+1;
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Writer writer = response.getWriter();
            writer.write(JsonUtils.blogToJson(blogs,pageNum,request));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}